const esclient = require('../services/elasticsearch');
const getNowFormatDate = () => {
    const date = new Date();
    const seperator1 = '-';
    let month = date.getMonth() + 1;
    let strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = '0' + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = '0' + strDate;
    }
    return date.getFullYear() + seperator1 + month + seperator1 + strDate;
};

//SELECT * FROM xyqb__h5intro_ext  WHERE submitstat="1" AND _type like '%2017-05-12%' AND isp='移动'
//SELECT provinceURLEnc,COUNT(*) FROM xyqb__h5intro_ext  WHERE _type like '%2017-05-12%' GROUP BY provinceURLEnc

exports.getApplyData = function (req, res, next) {
    const applyRegionPromise = esclient.search({
        'index': '*__login_ext',
        'body': {
            'from': 0,
            'size': 0,
            'query': {
                'filtered': {
                    'filter': {
                        'bool': {
                            'must': {
                                'query': {
                                    'match': {
                                        '_type': {
                                            'query': 'docs-' + getNowFormatDate(),
                                            'type': 'phrase'
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            },
            '_source': {
                'includes': [
                    'provinceURLEnc',
                    'COUNT'
                ],
                'excludes': []
            },
            'fields': 'provinceURLEnc',
            'aggregations': {
                'provinceURLEnc': {
                    'terms': {
                        'field': 'provinceURLEnc',
                        'size': 200
                    },
                    'aggregations': {
                        'COUNT(*)': {
                            'value_count': {
                                'field': '_index'
                            }
                        }
                    }
                }
            }
        }
    });
    const applyPeoplePromise = esclient.search({
        index: '*__login_ext',
        body: {
            'from': 0,
            'size': 50,
            'query': {
                'filtered': {
                    'filter': {
                        'bool': {
                            'must': {
                                'query': {
                                    'match': {
                                        '_type': {
                                            'query': 'docs-' + getNowFormatDate(),
                                            'type': 'phrase'
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            },
            'sort': [
                {
                    'lgntmstmp': {
                        'order': 'desc'
                    }
                }
            ]
        }
    });

    Promise.all([applyRegionPromise, applyPeoplePromise]).then(([applyRegionData, applyPeopleData]) => {
        let regionData = applyRegionData.aggregations.provinceURLEnc.buckets.map(item => {
            let province = decodeURIComponent(item.key.replace(/xy/g, '%'));
            return {
                name: province,
                value: item.doc_count
            };
        });
        let peopleData = applyPeopleData.hits.hits.map(item => {
            let province = decodeURIComponent(item._source.provinceURLEnc.replace(/xy/g, '%'));
            return {
                province,
                longitude: item._source.longitude,
                latitude: item._source.latitude,
                phone: item._source.phoneNumber
            };
        });
        res.json({
            applyRegion: {
                total: applyRegionData.hits.total,
                data: regionData
            },
            applyPeople: peopleData
        });
    });
};

exports.getApplyProduct = function (req, res, next) {
    const buildSearch = function (type) {
        return esclient.search({
            index: type + '__applyproduct-' + getNowFormatDate(),
            body: {
                'from': 0,
                'size': 0,
                '_source': {
                    'includes': [
                        'productno',
                        'COUNT'
                    ],
                    'excludes': []
                },
                'fields': 'productno',
                'aggregations': {
                    'productno': {
                        'terms': {
                            'field': 'productno',
                            'size': 200
                        },
                        'aggregations': {
                            'COUNT(*)': {
                                'value_count': {
                                    'field': '_index'
                                }
                            }
                        }
                    }
                }
            }
        });
    };
    // 随借随还、现金分期申请总数
    const xyqbApplyProductPromise = buildSearch('xyqb');
    const sjdApplyProductPromise = buildSearch('sjd');
    // 随借随还小时段申请数据
    const sjshPromise = esclient.search({
        index: '*__applyproduct-' + getNowFormatDate(),
        body: {
            'size': 0,
            'query': {
                'bool': {
                    'should': [
                        {
                            'match': {
                                'productno': '2017061510060016'
                            }
                        },
                        {
                            'match': {
                                'productno': '40000001'
                            }
                        }
                    ]
                }
            },
            'aggs': {
                'rangetime': {
                    'date_histogram': {
                        'field': '@timestamp',
                        'format': 'yyyy-MM-dd HH:mm:ss',
                        'interval': '3600s',
                        'min_doc_count': 0,
                        'order': {
                            '_key': 'asc'
                        }
                    },
                    'aggs': {
                        'mergeCount': {
                            'terms': {
                                'field': 'nglog.@fields.rgtstatus'
                            }
                        }
                    }
                }
            }
        }
    });
    // 现金分期小时段申请数据
    const xjfqPromise = esclient.search({
        index: '*__applyproduct-' + getNowFormatDate(),
        body: {
            'size': 0,
            'query': {
                'bool': {
                    'should': [
                        {
                            'match': {
                                'productno': '2017031116330013'
                            }
                        },
                        {
                            'match': {
                                'productno': '40000002'
                            }
                        }
                    ]
                }
            },
            'aggs': {
                'rangetime': {
                    'date_histogram': {
                        'field': '@timestamp',
                        'format': 'yyyy-MM-dd HH:mm:ss',
                        'interval': '3600s',
                        'min_doc_count': 0,
                        'order': {
                            '_key': 'asc'
                        }
                    },
                    'aggs': {
                        'mergeCount': {
                            'terms': {
                                'field': 'nglog.@fields.rgtstatus'
                            }
                        }
                    }
                }
            }
        }
    });
    Promise.all([xyqbApplyProductPromise, sjdApplyProductPromise, sjshPromise, xjfqPromise])
        .then(([xyqbApplyProductData, sjdApplyProductData, sjshData, xjfqData]) => {
            let obj = {
                xyqb: {
                    xjfqCount: 0,
                    sjshCount: 0
                },
                sjd: {
                    xjfqCount: 0,
                    sjshCount: 0
                },
                xjfq: {
                    line: []
                },
                sjsh: {
                    line: []
                }
            };
            xyqbApplyProductData.aggregations.productno.buckets.forEach(item => {
                if (item.key === '40000001') {
                    obj.xyqb.sjshCount = item.doc_count;
                } else if (item.key === '40000002') {
                    obj.xyqb.xjfqCount = item.doc_count;
                }
            });
            sjdApplyProductData.aggregations.productno.buckets.forEach(item => {
                if (item.key === '2017061510060016') {
                    obj.sjd.sjshCount = item.doc_count;
                } else if (item.key === '2017031116330013') {
                    obj.sjd.xjfqCount = item.doc_count;
                }
            });

            sjshData.aggregations.rangetime.buckets.pop();
            xjfqData.aggregations.rangetime.buckets.pop();
            obj.sjsh.line = sjshData.aggregations.rangetime.buckets.map(item => {
                return item.doc_count
            });
            obj.xjfq.line = xjfqData.aggregations.rangetime.buckets.map(item => {
                return item.doc_count
            });
            res.json(obj);
        })
};

exports.getApplyChannel = function (req, res, next) {
    esclient.search({
        index: '*__register_channeldeal-' + getNowFormatDate().substring(2),
        body: {
            'from': 0,
            'size': 0,
            '_source': {
                'includes': [
                    'top_channel_descURLEnc',
                    'COUNT'
                ],
                'excludes': []
            },
            'fields': 'top_channel_descURLEnc',
            'aggregations': {
                'top_channel_descURLEnc': {
                    'terms': {
                        'field': 'top_channel_descURLEnc',
                        'size': 200
                    },
                    'aggregations': {
                        'COUNT(*)': {
                            'value_count': {
                                'field': '_index'
                            }
                        }
                    }
                }
            }
        }
    }).then(response => {
        // let tmpArr = [];
        // let tmpCount = 0;
        let data = response.aggregations.top_channel_descURLEnc.buckets.map(item => {
            let channel = decodeURIComponent(item.key.replace(/xy/g, '%'));
            // if (channel === '安卓市场') {
            //     tmpCount = item.doc_count;
            // }
            // tmpArr = [
            //     {
            //         channel: '线下组',
            //         count: channel === '线下组' ? Math.round(item.doc_count + (tmpCount / 10 + 128)) :
            // Math.round(tmpCount / 10 + 128) } ];
            return {
                channel,
                count: item.doc_count
            };
        });
        // res.json([...data, ...tmpArr]);
        res.json(data);
    }).catch(err => {
        console.log(err);
    })
};
